#! /usr/bin/python




import tensorflow as tf
import tensorlayer as tl
from PIL import Image
import numpy as np
import sys
import matplotlib.image as mpimg # mpimg 用于读取图片
import matplotlib.pyplot as plt
def MatrixToImage(data):
    data = data*255
    new_im = Image.fromarray(data)
    return new_im


def rgb2gray(rgb):
    return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])


sess = tf.InteractiveSession()

# prepare data
X_train, y_train, X_val, y_val, X_test, y_test = \
                                tl.files.load_mnist_dataset(shape=(-1,784))
# define placeholder
x = tf.placeholder(tf.float32, shape=[None, 784], name='x')
y_ = tf.placeholder(tf.int64, shape=[None, ], name='y_')

# define the network
network = tl.layers.InputLayer(x, name='input_layer')
network = tl.layers.DropoutLayer(network, keep=0.8, name='drop1')
network = tl.layers.DenseLayer(network, n_units=800,
                                act = tf.nn.relu, name='relu1')
network = tl.layers.DropoutLayer(network, keep=0.5, name='drop2')
network = tl.layers.DenseLayer(network, n_units=800,
                                act = tf.nn.relu, name='relu2')
network = tl.layers.DropoutLayer(network, keep=0.5, name='drop3')


network = tl.layers.DenseLayer(network, n_units=10,
                                act = tf.identity,
                                name='output_layer')


load_params = tl.files.load_npz(path='', name='model.npz')
# print(load_params)
tl.files.assign_params(sess, load_params, network)



def predict(lena):

# lena = mpimg.imread(sys.argv[1])
    lena = rgb2gray(lena)
    # print("lena.shape",lena.shape)   
    # print(lena.shape)   

    lena=np.reshape(lena,(784,))

    # MatrixToImage(np.reshape(lena,(28,28))).show()
    # input()
    # print("lena.shape")
    # print(lena.shape)


    # define cost function and metric.
    # y = network.outputs
    # cost = tl.cost.cross_entropy(y, y_)
    # correct_prediction = tf.equal(tf.argmax(y, 1), y_)
    # acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    # tl.utils.test(sess, network, acc, xx, yy, x, y_, batch_size=None)

    # print(X_test[2])

    ###### Fri Jan 13 10:37:07 CST 2017

    xx=np.array([lena])

    y = network.outputs
    y_op = tf.argmax(tf.nn.softmax(y), 1)
    print("predict:")
    print(tl.utils.predict(sess, network, xx, x, y_op))




